package com.cac.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cac.oj.annotation.AuthCheck;
import com.cac.oj.common.BaseResponse;
import com.cac.oj.common.DeleteRequest;
import com.cac.oj.common.ErrorCode;
import com.cac.oj.common.ResultUtils;
import com.cac.oj.constant.UserConstant;
import com.cac.oj.exception.BusinessException;
import com.cac.oj.exception.ThrowUtils;
import com.cac.oj.model.dto.notice.*;
import com.cac.oj.model.entity.Notice;
import com.cac.oj.model.entity.User;
import com.cac.oj.model.vo.NoticeVO;
import com.cac.oj.service.NoticeService;
import com.cac.oj.service.UserService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/notice")
@Slf4j
public class NoticeController {
    @Resource
    private NoticeService noticeService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();
    /**
     * 创建
     *
     * @param noticeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addNotice(@RequestBody NoticeAddRequest noticeAddRequest, HttpServletRequest request) {
        if (noticeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeAddRequest, notice);
        noticeService.validNotice(notice, true);
        User loginUser = userService.getLoginUser(request);
        notice.setUserId(loginUser.getId());
        notice.setFavourNum(0);
        boolean result = noticeService.save(notice);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newNoticeId = notice.getId();
        return ResultUtils.success(newNoticeId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteNotice(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Notice oldNotice = noticeService.getById(id);
        ThrowUtils.throwIf(oldNotice == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldNotice.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = noticeService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param noticeUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateNotice(@RequestBody NoticeUpdateRequest noticeUpdateRequest) {
        if (noticeUpdateRequest == null || noticeUpdateRequest.getId()<=0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateRequest, notice);
        // 参数校验
        noticeService.validNotice(notice, false);
        long id = noticeUpdateRequest.getId();
        // 判断是否存在
        Notice oldNotice = noticeService.getById(id);
        ThrowUtils.throwIf(oldNotice == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = noticeService.updateById(notice);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Notice> getNoticeById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = noticeService.getById(id);
        if (notice == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
//        User loginUser = userService.getLoginUser(request);
//        //如果不是本人或管理员，不能获取全部信息
//        if(!notice.getUserId().equals(loginUser.getId()) && userService.isAdmin(loginUser)){
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        };
        return ResultUtils.success(notice);
    }

    /**
     * 根据 id 获取(脱敏)
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<NoticeVO> getNoticeVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = noticeService.getById(id);
        if (notice == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(noticeService.getNoticeVO(notice, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param noticeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<NoticeVO>> listNoticeVOByPage(@RequestBody NoticeQueryRequest noticeQueryRequest,
                                                               HttpServletRequest request) {
        long current = noticeQueryRequest.getCurrent();
        long size = noticeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Notice> noticePage = noticeService.page(new Page<>(current, size),
                noticeService.getQueryWrapper(noticeQueryRequest));
        return ResultUtils.success(noticeService.getNoticeVOPage(noticePage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param noticeEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editNotice(@RequestBody NoticeEditRequest noticeEditRequest, HttpServletRequest request) {
        if (noticeEditRequest == null || noticeEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeEditRequest, notice);
        // 参数校验
        noticeService.validNotice(notice, false);
        User loginUser = userService.getLoginUser(request);
        long id = noticeEditRequest.getId();
        // 判断是否存在
        Notice oldNotice = noticeService.getById(id);
        ThrowUtils.throwIf(oldNotice == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldNotice.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = noticeService.updateById(notice);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取公告列表（仅管理员）
     *
     * @param noticeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Notice>> listNoticeByPage(@RequestBody NoticeQueryRequest noticeQueryRequest,
                                                           HttpServletRequest request) {
        long current = noticeQueryRequest.getCurrent();
        long size = noticeQueryRequest.getPageSize();
        Page<Notice> noticePage = noticeService.page(new Page<>(current, size),
                noticeService.getQueryWrapper(noticeQueryRequest));
        return ResultUtils.success(noticePage);
    }

}
